export default class IndexedDBManager {
  constructor({ dbName = 'myDbName', storeName = 'myStoreName', version = 1, maxAge = 7 * 24 * 60 * 60 * 1000 }) {
    // 检查 IndexedDB 支持
    if (!window.indexedDB) {
      throw new Error('Your browser doesn\'t support IndexedDB')
    }

    this.dbName = dbName
    this.storeName = storeName
    this.version = version
    this.db = null
    this.maxAge = maxAge // 数据最大保存时间，默认7天
  }

  // 初始化数据库
  async initDatabase() {
    if (this.db) {
      return this.db
    }
    try {
      this.db = await new Promise((resolve, reject) => {
        const request = indexedDB.open(this.dbName, this.version)
        request.onupgradeneeded = event => {
          console.log('数据库升级需要')
          const db = event.target.result

          // 创建对象存储并设置 id 为主键
          if (!db.objectStoreNames.contains(this.storeName)) {
            // const store = db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true })
            const store = db.createObjectStore(this.storeName, { keyPath: 'id' })

            // 添加索引
            store.createIndex('timestamp', 'timestamp', { unique: false })
          }
        }

        request.onsuccess = () => {
          console.log('数据库连接成功')
          resolve(request.result)
        }
        request.onerror = () => reject(request.error)
      })

      // 定期清理过期数据
      //this._cleanExpiredData()

      return this.db
    } catch (error) {
      console.error('数据库初始化失败:', error)
      throw error
    }
  }

  // 保存数据到数据库
  async saveData(data) {
    try {
      // 添加时间戳
      const dataWithTimestamp = {
        ...data,
        timestamp: Date.now()
      }

      await new Promise((resolve, reject) => {
        const transaction = this.db.transaction([this.storeName], 'readwrite')
        const store = transaction.objectStore(this.storeName)

        transaction.oncomplete = () => resolve()
        transaction.onerror = () => reject(transaction.error)

        store.put(dataWithTimestamp)
      })

      //console.log('数据保存成功，ID:', data.id)
    } catch (error) {
      console.error('保存数据失败:', error)
      throw error
    }
  }

  // 批量保存数据
  async saveMultipleData(dataArray) {
    try {
      await new Promise((resolve, reject) => {
        const transaction = this.db.transaction([this.storeName], 'readwrite')
        const store = transaction.objectStore(this.storeName)

        transaction.oncomplete = () => resolve()
        transaction.onerror = () => reject(transaction.error)

        dataArray.forEach(data => {
          store.put({
            ...data,
            timestamp: Date.now()
          })
        })
      })

      console.log('批量数据保存成功')
    } catch (error) {
      console.error('批量保存数据失败:', error)
      throw error
    }
  }

  // 根据 id 获取数据，如果没有则保存默认数据并返回
  async getDataById(id) {
    try {
      const result = await new Promise((resolve, reject) => {
        const transaction = this.db.transaction([this.storeName], 'readonly')
        const store = transaction.objectStore(this.storeName)
        const request = store.get(id)

        request.onsuccess = () => resolve(request.result)
        request.onerror = () => reject(request.error)
      })

      if (result) {
        // 检查数据是否过期
        if (Date.now() - result.timestamp > this.maxAge) {
          await this.deleteData(id)
          return false
        }
        // console.log('成功获取数据:', id)
        return result
      }

     // console.log('未找到数据:', id)
      return false
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  // 删除数据
  async deleteData(id) {
    try {
      await new Promise((resolve, reject) => {
        const transaction = this.db.transaction([this.storeName], 'readwrite')
        const store = transaction.objectStore(this.storeName)
        const request = store.delete(id)

        request.onsuccess = () => resolve()
        request.onerror = () => reject(request.error)
      })

    //  console.log('数据删除成功:', id)
    } catch (error) {
      console.error('删除数据失败:', error)
      throw error
    }
  }

  // 清理过期数据
  async _cleanExpiredData() {
    try {
      const transaction = this.db.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const index = store.index('timestamp')
      const cutoffTime = Date.now() - this.maxAge

      const request = index.openCursor()

      request.onsuccess = event => {
        const cursor = event.target.result
        if (cursor) {
          if (cursor.value.timestamp < cutoffTime) {
            store.delete(cursor.value.id)
            console.log('已删除过期数据:', cursor.value.id)
          }
          cursor.continue()
        }
      }
    } catch (error) {
      console.error('清理过期数据失败:', error)
    }
  }

  // 获取数据库状态
  async getDBStatus() {
    try {
      const transaction = this.db.transaction([this.storeName], 'readonly')
      const store = transaction.objectStore(this.storeName)
      const countRequest = store.count()

      const count = await new Promise((resolve, reject) => {
        countRequest.onsuccess = () => resolve(countRequest.result)
        countRequest.onerror = () => reject(countRequest.error)
      })

      return {
        totalItems: count,
        dbName: this.dbName,
        storeName: this.storeName,
        version: this.version
      }
    } catch (error) {
      console.error('获取数据库状态失败:', error)
      throw error
    }
  }
}
